package asia.yuanding.wechat.web.netty.handler.impl;

import asia.yuanding.wechat.system.util.SystemUtil;
import asia.yuanding.wechat.web.entity.SessionInfo;
import asia.yuanding.wechat.web.entity.SessionList;
import asia.yuanding.wechat.web.entity.User;
import asia.yuanding.wechat.web.netty.handler.MessageHandlerUtil;
import asia.yuanding.wechat.web.netty.handler.annotation.MessageProcessor;
import asia.yuanding.wechat.web.netty.handler.annotation.NettyMessageHandler;
import asia.yuanding.wechat.web.netty.vo.Result;
import asia.yuanding.wechat.web.service.SessionInfoService;
import asia.yuanding.wechat.web.service.SessionListService;
import asia.yuanding.wechat.web.service.UserService;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会话相关消息处理器
 * 
 * @author Kiro
 */
@Slf4j
@NettyMessageHandler("session")
@Component
public class SessionMessageHandler {

    @Resource
    private SessionListService sessionListService;

    @Resource
    private SessionInfoService sessionInfoService;

    @Resource
    private UserService userService;

    @MessageProcessor("init")
    public String init(JSONObject reqEntity, ChannelHandlerContext ctx) {
        String uId = MessageHandlerUtil.getUId(ctx);

        User user = userService.lambdaQuery()
                .eq(User::getUid, uId)
                .one();
        Date lastTime = user.getLastTime();


        // 同步会话列表
        List<SessionList> sessionLists = sessionListService.lambdaQuery()
                .eq(SessionList::getCreateUser, uId)
                .ge(SessionList::getCreateTime, lastTime)
                .or()
                .ge(SessionList::getUpdateTime, lastTime)
                .orderByAsc(SessionList::getUpdateTime)
                .list();

        sessionLists.forEach(sessionList -> {
            ctx.channel().writeAndFlush(MessageHandlerUtil.getResult(Result.ok("initSession", sessionList)));
        });

        List<SessionList> sessionListList = sessionListService.lambdaQuery()
                .eq(SessionList::getCreateUser, uId)
                .list();

        List<String> allSessionIds = sessionListList.stream().map(SessionList::getSessionId)
                .collect(Collectors.toList());

        Map<String, SessionList> sessionListMap = sessionListList.stream()
                .distinct()
                .collect(Collectors.toMap(SessionList::getSessionId, item -> item));

        if (!allSessionIds.isEmpty()) {
            // 同步会话内消息
            List<SessionInfo> sessionInfoList = sessionInfoService.lambdaQuery()
                    .in(SessionInfo::getSessionId, allSessionIds)
                    .ge(SessionInfo::getCreateTime, lastTime)
                    .eq(SessionInfo::getCreateUser, uId)
                    .orderByAsc(SessionInfo::getCreateTime)
                    .list();



            sessionInfoList.forEach(sessionInfo -> {
                sessionInfo.setContactId(sessionListMap.get(sessionInfo.getSessionId()).getContactId());
                ctx.channel().writeAndFlush(MessageHandlerUtil.getResult(Result.ok("initSessionInfo", sessionInfo)));
            });

        }
        // 都同步完更新下当前同步时间
        userService.lambdaUpdate()
                .eq(User::getUid, uId)
                .update(new User(){{setLastTime(new Date());}});



        return null;
    }


}